'use strict';

const Controller = require('egg').Controller;

class DictDataController extends Controller {
  async index(){
    const {ctx,app} = this;
    // console.log(app.Sequelize.fn,9999999999)
    let option = ctx.helper.formatOptions(ctx.query,["dictType","dictName","status"]);
    option.order = app.Sequelize.col("dictSort");
    try {
      let result = await ctx.model.SysDictData.findAndCountAll(option);
      ctx.body = ctx.helper.formateResponseList(result);
    } catch (error) {
      ctx.body = ctx.helper.formateResponse(null,310,"查询失败")
    }
  }
  async findByType(){
    const {ctx} = this;
    const {id} = ctx.params;
    let result = await ctx.model.SysDictData.findAll({
      where:{
        dictType:id
      }
    });
    ctx.body=ctx.helper.formateResponse(result);
  }
  async create(){
    const {ctx} = this;
    const _data = ctx.request.body;
    const user = ctx.session.userinfo;
    const result = await ctx.model.SysDictData.findOne({
      where:{
        dictValue:_data.dictValue,
        dictType:_data.dictType
      }
    });
    if(!result){
      const _dict = Object.assign({},_data,{createBy:user.userName,updateBy:user.userName});
      const data = await ctx.model.SysDictData.create(_dict);
      ctx.body = ctx.helper.formateResponse(data);
    }else{
      ctx.body = ctx.helper.formateResponse(null,500,"字典类型重复");
    }
  }
  async show(){
    const {ctx} = this;
    const {id} = ctx.params;
    try {
      const result = await ctx.model.SysDictData.findByPk(Number(id));
      ctx.body = ctx.helper.formateResponse(result);
    } catch (error) {
      
    }
  }
  async update(){
    const {ctx} = this;
    const data = ctx.request.body;

    const list = await ctx.model.SysDictData.findAll({
      where:{
        dictValue:data.dictValue,
        dictType:data.dictType
      }
    });

    let result = null;
    if(list.length === 0){
      result = await ctx.model.SysDictData.findByPk(data.dictCode);;
    }else if(list.length === 1){
      let obj = list[0].toJSON();
      if(obj.dictCode === data.dictCode){
        result = list[0];
      }else{
        ctx.body = ctx.helper.formateResponse(null,500,"字段重复");
        return
      }
    }

    if(!result) return ctx.body = ctx.helper.formateResponse(null,500,"修改失败");
    const user = ctx.session.userinfo;
    result.update({
      status:data.status,
      dictLabel:data.dictLabel,
      dictValue:data.dictValue,
      dictSort:data.dictSort,
      remark:data.remark,
      updateBy:user.userName
    });
    ctx.body = ctx.helper.formateResponse(result);
  }
  async destroy(){
    const ctx = this.ctx;
    const id = ctx.params.id;
    const result = await ctx.model.SysDictData.findByPk(Number(id));
    if(result){
      await result.destroy();
    }else{
      ctx.body = ctx.helper.formateResponse(null,500,"删除失败");
      return
    }
    ctx.body = ctx.helper.formateResponse(null);
  }
}

module.exports = DictDataController;
